package com.dataaccess.dataaccess.web.service;


import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.druid.util.StringUtils;
import com.dataaccess.dataaccess.common.base.BaseService;
import com.dataaccess.dataaccess.common.utils.DataHand;
import com.dataaccess.dataaccess.model.AlarmAllDeviceDataChanged;
import com.dataaccess.dataaccess.model.AutoNetworkAlarmDeviceDataChanged;
import com.dataaccess.dataaccess.support.model.RespEntity;
import com.dataaccess.dataaccess.support.utils.HexUtils;
import com.dataaccess.dataaccess.web.mapper.AlarmAllDeviceDataChangedMapper;
import com.dataaccess.dataaccess.web.mapper.AutoNetworkAlarmDeviceDataChangedMapper;
import com.dataaccess.dataaccess.web.mapper.AutoNetworkNormalDeviceDataChangedMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;

/**
 * @Author: YangYu
 * @ClassName: AutoNetworkAlarmDeviceDataChangedService
 * @Date: Created in 10:14 2021/1/21
 * @Description: 自动联网服务
 */
@Service
public class AutoNetworkAlarmDeviceDataChangedService extends BaseService {

    @Resource
    private AutoNetworkAlarmDeviceDataChangedMapper autoNetworkAlarmDeviceDataChangedMapper;
    @Resource
    private AutoNetworkNormalDeviceDataChangedMapper autoNetworkNormalDeviceDataChangedMapper;
    @Resource
    private AsyncService asyncService;
    @Resource
    private AlarmAllDeviceDataChangedMapper alarmAllDeviceDataChangedMapper;

    /**
     * @Author YangYu
     * @Description 回调地址：设备数据变化，订阅后推送设备数据变化通知
     * @Date Created in 10:19 2021/1/21
     * @Param [s]
     */

    public boolean deviceDataChanged(String s)  {
        logger.info("自动联网服务："+s);

        String hjs[] = s.replace("\n","").split(" ");
        //探测器标志
        String detectorSign = hjs[0];
        //分机号
        String ext = String.valueOf(Long.parseLong(hjs[1]+hjs[2],16));
        //属性
        String attributes = String.valueOf(Long.parseLong(hjs[3],16));
        //回路
        String loop = String.valueOf(Long.parseLong(hjs[6],16));
        //机号
        String number = String.valueOf(Long.parseLong(hjs[7],16));
        //报警类型
        String alarmType = "";
        //报警内容
        String content = "";
        //报警时间
        String time = DateUtil.now();
        //报警原始数据
        AutoNetworkAlarmDeviceDataChanged autoNetworkAlarmDeviceDataChanged = new AutoNetworkAlarmDeviceDataChanged();
        autoNetworkAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
        autoNetworkAlarmDeviceDataChanged.setJsondata(s);
        autoNetworkAlarmDeviceDataChangedMapper.insert(autoNetworkAlarmDeviceDataChanged);
        boolean flag = false;
        if (detectorSign.equalsIgnoreCase("00")){
            alarmType = "探测器";
                        if (attributes.equals("0")){
                            content = "自动";
                        }else if (attributes.equals("1")){
                            content = "手动";
                        }else if (attributes.equals("2")){
                            content = "紧急";
                        }else if (attributes.equals("3")){
                            content = "测试";
                        }else if (attributes.equals("4")){
                            content = "误报";
                        }
            content = loop+"回路"+number+"号火警";
            flag = true;
        }else if(detectorSign.equalsIgnoreCase("05")) {
            alarmType = "有害气体";
            if (attributes.equals("10")){
                content = "一级告警";
            }else if (attributes.equals("11")){
                content = "一级告警恢复";
            }else if (attributes.equals("12")){
                content = "二级告警";
            }else if (attributes.equals("13")){
                content = "二级告警恢复";
            }
            flag = true;
        }else if(detectorSign.equalsIgnoreCase("06")) {
            alarmType = "模块输入";
            if (attributes.equals("0")){
                content = loop+"回路"+number+"号停止";
            }else if (attributes.equals("1")){
                content = loop+"回路"+number+"号启动";
            }else if (attributes.equals("2")){
                content = loop+"回路"+number+"号请求";
            }
            flag = true;
        }else if(detectorSign.equalsIgnoreCase("0D")) {
            alarmType = "故障";
            if (attributes.equals("0")){
                content = loop+"回路"+number+"号探测器故障";
            }else if (attributes.equals("1")){
                content = loop+"回路"+number+"号模块故障";
            }
            flag = true;
        }else if(detectorSign.equalsIgnoreCase("0E")) {
            alarmType = "故障恢复";
            if (attributes.equals("0")){
                content = loop+"回路"+number+"号探测器故障恢复";
            }else if (attributes.equals("1")){
                content = loop+"回路"+number+"号模块故障恢复";
            }
            flag = true;
        }else if(detectorSign.equalsIgnoreCase("0F")) {
            alarmType = "系统事件";
            content = getContent(attributes);
            flag = true;
        }
        String strs = "报警类型:"+alarmType+"\n"+
                "报警内容:"+content+"\n"+
                "分机号:"+ext+"\n"+
                "报警时间:"+time+"\n";
        System.out.println(strs);
        JSONObject jsonParamN = new JSONObject();
        if (flag == true) {
            jsonParamN.put("number", ext);
            jsonParamN.put("interfaceType", "1");
            jsonParamN.put("content", content);
            jsonParamN.put("alarmTypeName", alarmType);
            jsonParamN.put("alarmtime", time);
            jsonParamN.put("deviceClassify", 5);
            fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
            System.out.println(jsonParamN);
        }
        return flag;
    }
    /**
     * @Author YangYu
     * @Description 金盾用户传输装置（JB_QB_F52）
     * @Date Created in 16:20 2022/1/12
     * @Param [jsonParam]
     */

    public RespEntity JB_QB_F52(JSONObject jsonParam){
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("JB_QB_F52");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        String data = jsonParam.getStr("data");
        //主机号
        String source =data.substring(24,36);
        //0021cf230620
        String sourceNum =source.substring(10,12)+source.substring(8,10)+source.substring(6,8)
                +source.substring(4,6)+source.substring(2,4)+source.substring(0,2);
        //命令字
        String commandWord = data.substring(52,54);

        //不是心跳数据
        if (!"99".equals(commandWord)){
            //主机号
            Integer hostNumber = hexToInt(data.substring(60,62));
            //部件id
            String deviceId  = data.substring(64,72);
            //回路
            Integer loop = hexToInt(parsing(deviceId.substring(0,4)));
            //机号
            Integer machineNumber = hexToInt(parsing(deviceId.substring(4,8)));
            //报警类型
            String alarmTypeName = "";
            //报警内容
            String content = "";
            //报警标识
            boolean flag = false;
            //发送传输装置所连接控制器等系统的火警信息
            if ("9a".equals(commandWord)){
                alarmTypeName = "火警";
                content = loop+"回路"+machineNumber+"号火警";
                flag = true;
                //发送传输装置所连接控制器等系统除火警信息外的其他信息
            }else if ("9b".equals(commandWord)){
                //状态
                String state = data.substring(72,74);
                if (state.equals("03")){
                    alarmTypeName = "故障";
                    content = loop+"回路"+machineNumber+"号故障";
                    flag = true;
                }
            }
            if (flag){
                JSONObject jsonParamN = new JSONObject();
                jsonParamN.put("deviceClassify","5");
                //f52设备号+主机号+回路+地址号
                jsonParamN.put("number",sourceNum+hostNumber+loop+machineNumber);
                jsonParamN.put("interfaceType","1");
                jsonParamN.put("alarmtime",DateUtil.now());
                jsonParamN.put("alarmTypeName",alarmTypeName);
                jsonParamN.put("content",content);
                //rest
                System.out.println("GST200___________"+jsonParamN);
                //异步更新维保部件状态
                asyncService.updateFireFightingPartsState(jsonParamN.getStr("number"));
                fireFightingiot(jsonParamN,"communication","notificationAlarmHandel","alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
            //报警原始数据存储
            AutoNetworkAlarmDeviceDataChanged autoNetworkAlarmDeviceDataChanged = new AutoNetworkAlarmDeviceDataChanged();
            autoNetworkAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
            autoNetworkAlarmDeviceDataChanged.setJsondata(data);
            autoNetworkAlarmDeviceDataChanged.setType("JB_QB_F52");
            autoNetworkAlarmDeviceDataChangedMapper.insert(autoNetworkAlarmDeviceDataChanged);
        }else {
            JSONObject jsonParamN = new JSONObject();
            //异步更新设备状态
            jsonParamN.put("number",sourceNum);
            jsonParamN.put("time",DateUtil.now());
            asyncService.update_user_transmission_state(jsonParamN);
        }
        return RespEntity.success();
    }



    /**
     * @Author YangYu
     * @Description 大华用户传输装置
     * @Date Created in 14:11 2023/9/21
     * @Param [jsonParam]
     */

    public RespEntity autoNetDahua(JSONObject jsonParam){
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("autoNetDahua");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        //用于下发指令设备ID
        String dev_id = jsonParam.getStr("dev_id");
        //数据
        String code = jsonParam.getStr("code");
        //时间
        String realTime = DateUtil.now();
        //报警类型
        String alarmTypeName = "";
        //报警内容
        String content = "";
        //主机号
//        System.out.println(code.substring(24,36));
//        System.out.println(code.substring(24,26)+code.substring(26,28)+code.substring(28,30)+code.substring(30,32)+code.substring(32,34)+code.substring(34,36));
//        System.out.println(code.substring(34,36)+code.substring(32,34)+code.substring(30,32)+code.substring(28,30)+code.substring(26,28)+code.substring(24,26));
        Integer hostNumber = hexToInt(code.substring(34,36)+code.substring(32,34)+code.substring(30,32)+code.substring(28,30)+code.substring(26,28)+code.substring(24,26));
        //平台设备编号
        String number = "";
        //报警标识
        boolean flag = false;
        JSONObject jsonParamN = new JSONObject();
        //注册包、心跳
        if (code.startsWith("0000", 48)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "今日数据变化");
            jsonObject.put("value", 0);
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);
            //rest调用平时数据添加接口：
            jsonParamN.put("paraminfo", jsonArray);
            jsonParamN.put("number", hostNumber);
            jsonParamN.put("time", realTime);
            //return RespEntity.success(jsonParamN);
            fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
            //异步更新部件状态
            asyncService.update_user_transmission_state(jsonParamN);
        }else {
            //40 40 08 00 01 02 12 38 0e 0d 03 11 c8 00 00 00 00 00 64 00 00 00 00 00 0a 00 02 18 01 04 01 12 38 0e 0d 03 11 53 23 23
            //40 40 05 00 01 02 08 1b 13 10 03 11 d8 27 00 00 00 00 64 00 00 00 00 00 09 00 02 15 01 02 07 1b 13 10 03 11 41 23 23
            //类型标志
            Integer type = hexToInt(code.substring(54,56));
            //上传用户信息传输装置操作信息
            if (type == 24){
                number = hostNumber.toString();
                //标志位（二进制）
                String bit = HexUtils.hexToBinaryString(code.substring(58,60));
                if (bit.charAt(1) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传测试、";
                    flag = true;
                }
                if (bit.charAt(2) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传确认、";
                    flag = true;
                }
                if (bit.charAt(3) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传自检、";
                    flag = true;
                }
                if (bit.charAt(4) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传警情消除、";
                    flag = true;
                }
                if (bit.charAt(5) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传手动报警、";
                    flag = true;
                }
                if (bit.charAt(6) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传消音、";
                    flag = true;
                }
                if (bit.charAt(7) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传复位、";
                    flag = true;
                }
            //上传用户信息传输装置运行状态
            }else if (type == 21){
                number = hostNumber.toString();
                //标志位（二进制）
                String bit = HexUtils.hexToBinaryString(code.substring(58,60));
                if (bit.charAt(1) == '1'){
                    alarmTypeName = "故障";
                    content = content+"用传监测连接线路故障、";
                    flag = true;
                }
//                if (bit.charAt(2) == '1'){
//                    alarmTypeName = "故障";
//                    content = content+"用传与监控中心通信信道故障、";
//                    flag = true;
//                }
                if (bit.charAt(3) == '1'){
                    alarmTypeName = "故障";
                    content = content+"用传备电故障、";
                    flag = true;
                }
                if (bit.charAt(4) == '1'){
                    alarmTypeName = "故障";
                    content = content+"用传主电故障、";
                    flag = true;
                }
                if (bit.charAt(5) == '1'){
                    alarmTypeName = "故障";
                    content = content+"用传故障、";
                    flag = true;
                }
                if (bit.charAt(6) == '1'){
                    alarmTypeName = "火警";
                    content = content+"用传火警、";
                    flag = true;
                }
                if (bit.charAt(7) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传正常监视、";
                    flag = true;
                }
            //上传建筑消防设施部件运行状态
            } else if (type == 2){

                // 40 40 06 00 01 02 09 10 0a 12 04 13 c8 00 00 00 00 00 64 00 00 00 00 00 30 00 02 02 01 1a 01 00 27 00 01 00 02 00 32 46 c3 c5 cc fc 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 10 0a 12 04 13 0c 23 23
                // 40 40 05 00 01 02 08 1b 13 10 03 11 d8 27 00 00 00 00 64 00 00 00 00 00 09 00 02 15 01 02 07 1b 13 10 03 11 41 23 23
                //系统类型
                Integer syType = hexToInt(code.substring(58,60));
                //系统名称
                String syName = "";
                if (syType == 0){
                    syName = "通用";
                }else if (syType == 1){
                    syName = "火灾报警系统";
                }else if (syType == 10){
                    syName = "消防联动控制器";
                }else if (syType == 11){
                    syName = "消防栓系统";
                }else if (syType == 12){
                    syName = "自动喷水灭火系统";
                }else if (syType == 13){
                    syName = "气体灭火系统";
                }else if (syType == 14){
                    syName = "水喷雾灭火系统（泵启动方式）";
                }else if (syType == 15){
                    syName = "水喷雾灭火系统（压力容器启动方式）";
                }else if (syType == 16){
                    syName = "泡沫灭火系统";
                }else if (syType == 17){
                    syName = "干粉灭火系统";
                }else if (syType == 18){
                    syName = "防烟排烟系统";
                }else if (syType == 19){
                    syName = "防火门及卷帘系统";
                }else if (syType == 20){
                    syName = "消防电梯";
                }else if (syType == 21){
                    syName = "消防应急广播";
                }else if (syType == 22){
                    syName = "消防应急照明和疏散指示系统";
                }else if (syType == 23){
                    syName = "消防电源";
                }else if (syType == 24){
                    syName = "消防电话";
                }else {
                    syName = "预留、用户自定义";
                }
                //部件类型
                Integer componentType = hexToInt(code.substring(62,64));
                //部件名称
                String componentName = getComponentName(componentType);
                //部件地址
                String componentCode = getComponentCode(code.substring(64,72));
                number = hostNumber+componentCode;
                //部件状态
                //标志位（二进制）
                String bitcode =code.substring(72,76);
                String bit = HexUtils.hexToBinaryString(bitcode.substring(2,4)+bitcode.substring(0,2));
                if (bit.charAt(7) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"正常运行状态、";
                    flag = true;
                }
                if (bit.charAt(6) == '1'){
                    alarmTypeName = "火警";
                    content = content+"火警、";
                    flag = true;
                }
                if (bit.charAt(5) == '1'){
                    alarmTypeName = "故障";
                    content = content+"故障、";
                    flag = true;
                }
                if (bit.charAt(4) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"屏蔽、";
                    flag = true;
                }
                if (bit.charAt(3) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"监管、";
                    flag = true;
                }
                if (bit.charAt(2) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"启动、";
                    flag = true;
                }
                if (bit.charAt(1) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"反馈、";
                    flag = true;
                }
                if (bit.charAt(0) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"延时状态、";
                    flag = true;
                }
                if (flag){
                    content = syName+"、"+componentName+"、"+content;
                }
            }
            if (flag){
                jsonParamN.put("deviceClassify","5");
                jsonParamN.put("number",number);
                jsonParamN.put("interfaceType","1");
                jsonParamN.put("alarmtime",realTime);
                jsonParamN.put("alarmTypeName",alarmTypeName);
                jsonParamN.put("content",content.substring(0,content.length()-1));
                //rest
                System.out.println("GST200___________"+jsonParamN);
                fireFightingiot(jsonParamN,"communication","notificationAlarmHandel","alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        }

        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 部件地址解析（大华）
     * @Date Created in 16:39 2023/9/25
     * @Param [componentCode]
     */

    public static String getComponentCode(String componentCode){
        String code = Integer.toString(hexToInt(componentCode.substring(2,4)+componentCode.substring(0,2)));
        if (code.length() == 1){
            code = "000"+code;
        }else if (code.length() == 2){
            code = "00"+code;
        }else if (code.length() == 3){
            code = "0"+code;
        }
        String loop = Integer.toString(hexToInt(componentCode.substring(6,8)+componentCode.substring(4,6)));
        if (loop.length() == 1){
            loop = "000"+loop;
        }else if (loop.length() == 2){
            loop = "00"+loop;
        }else if (loop.length() == 3){
            loop = "0"+loop;
        }
        return loop+code;
    }
    /**
     * @Author YangYu
     * @Description 部件名称解析（大华）
     * @Date Created in 16:09 2023/9/25
     * @Param [componentType]
     */

    public static String getComponentName(Integer componentType){
        //部件名称
        String componentName = "";
        if (componentType == 0){
            componentName = "通用";
        }else if (componentType == 1){
            componentName = "火灾报警控制器";
        }else if (componentType == 10){
            componentName = "可燃气体探铡器";
        }else if (componentType == 11){
            componentName = "点型可燃气体探测器";
        }else if (componentType == 12){
            componentName = "独立式可燃气体探测器";
        }else if (componentType == 13){
            componentName = "线型可燃气体探测器";
        }else if (componentType == 16){
            componentName = "电气火灾监控报警器";
        }else if (componentType == 17){
            componentName = "剩余电流式电气火灾监控探测器";
        }else if (componentType == 18){
            componentName = "测温式电气火灾监控探测器";
        }else if (componentType == 21){
            componentName = "探测回路";
        }else if (componentType == 22){
            componentName = "火灾显示盘";
        }else if (componentType == 23){
            componentName = "手动火灾报警按钮";
        }else if (componentType == 24){
            componentName = "消火栓按钮";
        }else if (componentType == 25){
            componentName = "火灾探测器";
        }else if (componentType == 30){
            componentName = "感温火灾探测器";
        }else if (componentType == 31){
            componentName = "点型感温火灾探测器";
        }else if (componentType == 32){
            componentName = "点型感温火灾探测器(s型)";
        }else if (componentType == 33){
            componentName = "点型感温火灾探测器(R型)";
        }else if (componentType == 34){
            componentName = "线型感温火灾探测器";
        }else if (componentType == 35){
            componentName = "线型感温火灾探测器(S型)";
        }else if (componentType == 36){
            componentName = "线型感温火灾探测器(R型)";
        }else if (componentType == 37){
            componentName = "光纤感温火灾探测器";
        }else if (componentType == 40){
            componentName = "感烟火灾探测器";
        }else if (componentType == 41){
            componentName = "点型离子感烟火灾探测器";
        }else if (componentType == 42){
            componentName = "点型光电感烟火灾探测器";
        }else if (componentType == 43){
            componentName = "线型光束感烟火灾探测器";
        }else if (componentType == 44){
            componentName = "吸气式感烟火灾探测器";
        }else if (componentType == 50){
            componentName = "复合式火灾探测器";
        }else if (componentType == 51){
            componentName = "复合式感烟感温火灾探测器";
        }else if (componentType == 52){
            componentName = "复合式感光感温火灾探浏器";
        }else if (componentType == 53){
            componentName = "复合式感光感烟火灾探测器";
        }else if (componentType == 61){
            componentName = "紫外火焰探测器";
        }else if (componentType == 62){
            componentName = "红外火焰探测器";
        }else if (componentType == 69){
            componentName = "感光火灾探测器";
        }else if (componentType == 74){
            componentName = "气体探测器";
        }else if (componentType == 78){
            componentName = "图像摄像方式火灾探测器";
        }else if (componentType == 79){
            componentName = "感声火灾探测器";
        }else if (componentType == 81){
            componentName = "气体灭火控制器";
        }else if (componentType == 82){
            componentName = "消防电气控制装置";
        }else if (componentType == 83){
            componentName = "消防控制室图形显示装置";
        }else if (componentType == 84){
            componentName = "模块";
        }else if (componentType == 85){
            componentName = "输入模块";
        }else if (componentType == 86){
            componentName = "输出模块";
        }else if (componentType == 87){
            componentName = "输入／输出模块";
        }else if (componentType == 88){
            componentName = "中继模块";
        }else if (componentType == 91){
            componentName = "消防水泵";
        }else if (componentType == 92){
            componentName = "消防水箱";
        }else if (componentType == 95){
            componentName = "喷淋泵";
        }else if (componentType == 96){
            componentName = "水流指示器";
        }else if (componentType == 97){
            componentName = "信号阀";
        }else if (componentType == 98){
            componentName = "报警阀";
        }else if (componentType == 99){
            componentName = "压力开关";
        }else if (componentType == 101){
            componentName = "阀驱动装置";
        }else if (componentType == 102){
            componentName = "防火门";
        }else if (componentType == 103){
            componentName = "防火阀";
        }else if (componentType == 104){
            componentName = "通风空调";
        }else if (componentType == 105){
            componentName = "泡沫液泵";
        }else if (componentType == 106){
            componentName = "管网电磁阀";
        }else if (componentType == 111){
            componentName = "防烟排烟风机";
        }else if (componentType == 113){
            componentName = "排烟防火阀";
        }else if (componentType == 114){
            componentName = "常闭送风口";
        }else if (componentType == 115){
            componentName = "排烟口";
        }else if (componentType == 116){
            componentName = "电控挡烟垂壁";
        }else if (componentType == 117){
            componentName = "防火卷帘控制器";
        }else if (componentType == 118){
            componentName = "防火门监控器";
        }else if (componentType == 121){
            componentName = "警报装置";
        }else {
            componentName = "预留、用户自定义";
        }
        return componentName;
    }
    /**
     * @Author YangYu
     * @Description 回路机号解析
     * @Date Created in 16:46 2022/1/12
     * @Param [devId]
     */

    public static String parsing(String devId){
        String id = "";
        if (devId.substring(0, 4).equals("0000")) id = "0";
        else if (devId.substring(0, 3).equals("000")) id = devId.substring(3, 4);
        else if (devId.substring(0, 2).equals("00")) id = devId.substring(2, 4);
        else if (devId.substring(0, 1).equals("0")) id = devId.substring(1, 4);
        return id;
    }
    /**
     * @Author YangYu
     * @Description 十六进制转十进制
     * @Date Created in 16:37 2022/1/12
     * @Param [hex]
     */

    public static int hexToInt(String hex){
        if (hex.length() < 1){
            return 0;
        }else {
            return Integer.parseInt(hex,16);
        }
    }
    public static void main(String[] args) {
        System.out.println(hexToInt("0000000027d8"));
    }
    //BCD码转为10进制串
    public static String bcd2Str(byte[] bytes){
        StringBuffer temp=new StringBuffer(bytes.length*2);

        for(int i=0;i<bytes.length;i++){
            temp.append((byte)((bytes[i]& 0xf0)>>>4));
            temp.append((byte)(bytes[i]& 0x0f));
        }
        return temp.toString().substring(0,1).equalsIgnoreCase("0")?temp.toString().substring(1):temp.toString();
    }
    //把16进制字符串转换成字节数组
    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

    /**
     * @Author YangYu
     * @Description 系统事件
     * @Date Created in 11:41 2021/1/19
     * @Param [code]
     */

    public static String getContent(String code) {
        Map<String, String> map = new HashMap<>();
        //报警数据
        map.put("0", "控制器复位");
        map.put("1", "控制器消音");
        map.put("2", "通讯网络故障");
        map.put("3", "通讯设备主电故障");
        map.put("4", "通讯设备备电故障");
        map.put("5", "查岗有应答");
        map.put("6", "查岗无应答");
        map.put("7", "巡检正常");
        map.put("8", "巡检不正常");
        map.put("9", "查岗失败");
        map.put("10", "联动---请求 ");
        map.put("11", "设置正常");
        map.put("12", "设置失败");
        map.put("13", "控制器主电故障");
        map.put("14", "控制器备电故障");
        map.put("15", "通讯设备主电故障恢复");
        map.put("16", "通讯设备备电故障恢复");
        map.put("17", "控制器主电故障恢复");
        map.put("18", "控制器备电故障恢复");
        map.put("19", "通讯故障恢复");
        map.put("20", "设备公共故障");
        map.put("21", "设备公共故障恢复");
        map.put("22", "控制器开机");
        map.put("23", "控制器关机");
        map.put("26", "联动--回答");
        map.put("27", "联动--回答消除");
        return map.get(code);
    }
    /**
     * @Author YangYu
     * @Description 用传接口（python调用）
     * @Date Created in 13:52 2021/7/26
     * @Param [str]
     */

    public RespEntity deviceDataChangedHX100(JSONObject jsonParam)  {
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("HX100");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        //String str = "7B 7B 7B 07 55 00 00 07 01 01 0E 16 30 35 31 31 37 31 00 00 00 00 00 00 00 00 00 00 00 00 00 100 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 100 15 05 18 0C 27 2F BD ";
        String str = jsonParam.getStr("code");
        String hjs[] = str.replace("\n","").split(" ");
        //包头7b7b7b07550000070201010b3035313037360000000000000000000000000000003118674687002000200020002000000000000015071a0e072959
        String baotou = str.substring(0,6);
        //用传网关ID
        String usePassGatewayID = "";
        //时间
        String realTime = "";
        //报警类型
        String alarmTypeName = "";
        //设备编号
        String detectorCode = "";
        //报警内容
        String content = "";
        //报警标识
        boolean flag = false;
        //心跳7a7a07550000071508050e3929e9
        if (baotou.contains("7a7a")){
            //用传网关ID
            usePassGatewayID = str.substring(4,14);
            realTime = hxTime(str.substring(14,26));
            //报警
        } else if (baotou.equalsIgnoreCase("7B7B7B")){
            //用传网关ID
            usePassGatewayID = str.substring(6,16);
            //网关类型
            String communicationType = str.substring(16,18);
            //系统类型
            String systemType = str.substring(18,20);
            //信息类型
            String informationType = str.substring(20,22);
            //状态字
            String statusWord = str.substring(22,24);
            //设备编号
            detectorCode = convertHexToString(str.substring(24,64));
            //位置信息（10 个汉字或 20个字母）
            String locationInformation = str.substring(64,104);
            //时间
            realTime = hxTime(str.substring(104,116));
            String content1 = getSystemType(systemType);
            String content2 = getInformationType(informationType);
            if (informationType.equals("01")) {
                alarmTypeName = "火警";
            } else if (informationType.equals("07")) {
                alarmTypeName = "故障";
            }else {
                alarmTypeName = "系统事件";
            }
            String content3 = "";
            //信息类型小于 20H 时
            if (hex16To10(informationType) < 32) {
                content3 = getDetectorType(hex16To10(statusWord)+"");
                //信息类型大于等于20H 时
            } else {
                content3 = getStatusWord(hex16To10(statusWord)+"");
            }
            content =content1+","+content2+","+content3;
            flag = true;
        }
        //为报警
        JSONObject jsonParamN = new JSONObject();
        if (flag){
            jsonParamN.put("deviceClassify","5");
            jsonParamN.put("number",usePassGatewayID+detectorCode);
            jsonParamN.put("interfaceType","1");
            jsonParamN.put("alarmtime",realTime);
            jsonParamN.put("alarmTypeName",alarmTypeName);
            jsonParamN.put("content",content);
            //报警原始数据存储
            AutoNetworkAlarmDeviceDataChanged autoNetworkAlarmDeviceDataChanged = new AutoNetworkAlarmDeviceDataChanged();
            autoNetworkAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
            autoNetworkAlarmDeviceDataChanged.setJsondata(str);
            autoNetworkAlarmDeviceDataChanged.setType("HX100");
            autoNetworkAlarmDeviceDataChangedMapper.insert(autoNetworkAlarmDeviceDataChanged);
            //rest
            System.out.println("GST200___________"+jsonParamN);
            //异步更新维保部件状态
            asyncService.updateFireFightingPartsState(jsonParamN.getStr("number"));
            fireFightingiot(jsonParamN,"communication","notificationAlarmHandel","alarmInfo");
            //异步更新设备状态
            jsonParamN.put("state","2");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "今日数据变化");
            jsonObject.put("value", 0);
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);
            //rest调用平时数据添加接口：
            jsonParamN.put("paraminfo", jsonArray);
            jsonParamN.put("number", usePassGatewayID);
            jsonParamN.put("time", realTime);
            //return RespEntity.success(jsonParamN);
            fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
            //更新部件状态
            asyncService.update_user_transmission_state(jsonParamN);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description sos一键报警（派安）
     * @Date Created in 13:52 2021/7/26
     * @Param [str]
     */

    public RespEntity deviceDataChangedSOS(JSONObject jsonParam) throws Exception {
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("paiAnSOS");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        if (!jsonParam.containsKey("payload")){
            return RespEntity.success();
        }
        //报警数据
        String data = HexUtil.encodeHexStr(Base64Decoder.decode(jsonParam.getJSONObject("payload").getStr("APPdata")));
        //设备号
        String number = jsonParam.getStr("IMEI");
        //报警时间
        String time = contextLoads(jsonParam.getLong("timestamp"));
        //命令a801000007 030101030b1564
        String command = data.substring(10,12);
        //信息类型
        String informationType = data.substring(14,16);
        //报警类型
        String alarmTypeName = "";
        //报警内容
        String content = "";
        //报警标识
        boolean flag = false;
        //心跳7a7a07550000071508050e3929e9
        if (command.equals("03")){
            if (informationType.equals("01")) {
                alarmTypeName = "火警";
                content = "手报报警";
            } else if (informationType.equals("02")) {
                alarmTypeName = "故障";
                content = "手报低电";
            }else {
                alarmTypeName = "系统事件";
                content = "设备事件为定义";
            }
            flag = true;
        }
        //为报警
        JSONObject jsonParamN = new JSONObject();
        if (flag){
            jsonParamN.put("deviceClassify","5");
            jsonParamN.put("number",number);
            jsonParamN.put("interfaceType","1");
            jsonParamN.put("alarmtime",time);
            jsonParamN.put("alarmTypeName",alarmTypeName);
            jsonParamN.put("content",content);
            fireFightingiot(jsonParamN,"communication","notificationAlarmHandel","alarmInfo");
            //异步更新设备状态
            jsonParamN.put("state","2");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "今日数据变化");
            jsonObject.put("value", 0);
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);
            //rest调用平时数据添加接口：
            jsonParamN.put("paraminfo", jsonArray);
            jsonParamN.put("number", number);
            jsonParamN.put("time", time);
            //return RespEntity.success(jsonParamN);
            fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
            //异步更新设备状态
            jsonParamN.put("state","1");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        return RespEntity.success();
    }



    /**
     * xulumin
     * 无线消防声光报警系统（派安PS-108 NB）
     * @param jsonParam
     * @return
     * @throws Exception
     */
    public RespEntity deviceDataHandSOS(JSONObject jsonParam) throws Exception {
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("paiAnSOS");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        if (!jsonParam.containsKey("payload")) {
            return RespEntity.success();
        }
        //报警数据
        String hexStr = HexUtil.encodeHexStr(Base64Decoder.decode(jsonParam.getJSONObject("payload").getStr("APPdata")));
        List<String> data = DataHand.formatData(hexStr);
//        List<String> data = DataHand.formatData("");
        //设备号
        String number = jsonParam.getStr("IMEI");
        //报警时间
        String time = contextLoads(jsonParam.getLong("timestamp"));
        // 指令
        String command = data.get(5);
        // 指令类型
        String informationType = data.get(6);
        // 报警、故障类型
        String alarmType = "";
        // 警报等级
        String alarmlevel = "";
//        String alarmlevel = data.get(8);
        // 警报内容
        String alarmContent = "";
        // 报警类型
        String alarmTypeName = "";
        // 报警内容
        String content = "";
        // 报警标识
        boolean flag = false;
        // 信号强度
        String signal = "";
        // 设备Id
        String deviceId = "";
        // 设备类型
        String deviceType = "";
        // 网关编号
        String gateWayNember = "";
        // 在线标志
        String mark = "";
        // 防区号
        String areaNumber = "";
        // 警报数据
        List<String> value = new ArrayList<>();

        // 判断消息类型
        if ("03".equals(command)) {// 报警、故障
            alarmType = data.get(7);
            flag = true;
            // 判断报警类型和警告内容
            if ("01".equals(alarmType)) {
                alarmContent = data.get(9);
                alarmTypeName = "火警";
                // 判断警告内容
                switch (alarmContent) {
                    case "03":
                        content = "发生火警";
                        break;
                    case "05":
                        content = "温度报警";
                        break;
                    case "08":
                        content = "SOS报警";
                        break;
                    case "09":
                        content = "电气报警";
                        break;
                    case "0A":
                        content = "水压报警";
                        break;
                    case "0B":
                        content = "手报报警";
                        break;
                    case "0C":
                        content = "一氧化碳报警";
                        break;
                    case "0D":
                        content = "烟温报警";
                        break;
                    case "0F":
                        content = "燃气报警";
                        break;
                    case "30":
                        content = "湿度报警";
                        break;
                    case "31":
                        content = "电压报警";
                        break;
                    case "32":
                        content = "电流报警";
                        break;
                    case "33":
                        content = "A相电压报警";
                        break;
                    case "34":
                        content = "B相电压报警";
                        break;
                    case "35":
                        content = "C相电压报警";
                        break;
                    case "36":
                        content = "A相电流报警";
                        break;
                    case "37":
                        content = "B相电流报警";
                        break;
                    case "38":
                        content = "C相电流报警";
                        break;
                    case "39":
                        content = "漏电流报警";
                        break;
                    case "3A":
                        content = "温度1报警";
                        break;
                    case "3B":
                        content = "温度2报警";
                        break;
                    case "3C":
                        content = "温度3报警";
                        break;
                    case "3D":
                        content = "温度4报警";
                        break;
                    case "3E":
                        content = "联动报警";
                        break;
                    case "40":
                        content = "主动拆防报警";
                        break;
                    case "4F":
                        content = "测试";
                        break;
                    case "50":
                        content = "门磁报警";
                        break;
                    case "51":
                        content = "断电报警";
                        break;
                    case "52":
                        content = "门磁打开";
                        break;
                    default:
                        content = "未匹配";
                }
            } else {
//                alarmTypeName = "故障";
                alarmContent = data.get(9);
                alarmTypeName = "火警";
                // 判断警告内容
                switch (alarmContent) {
                    case "03":
                        content = "烟感丢失";
                        break;
                    case "05":
                        content = "温感丢失";
                        break;
                    case "08":
                        content = "按钮丢失";
                        break;
                    case "09":
                        content = "电气丢失";
                        break;
                    case "0A":
                        content = "水压丢失";
                        break;
                    case "0B":
                        content = "手报丢失";
                        break;
                    case "0C":
                        content = "一氧化碳丢失";
                        break;
                    case "0D":
                        content = "烟温丢失";
                        break;
                    case "0F":
                        content = "燃气丢失";
                        break;
                    case "13":
                        content = "烟感低电";
                        break;
                    case "15":
                        content = "温感低电";
                        break;
                    case "18":
                        content = "按钮低电";
                        break;
                    case "1B":
                        content = "手报低电";
                        break;
                    case "1C":
                        content = "一氧化碳低电";
                        break;
                    case "1D":
                        content = "烟温低电";
                        break;
                    case "1F":
                        content = "燃气故障";
                        break;
                    case "2B":
                        content = "手报拆开";
                        break;
                    case "2D":
                        content = "烟温拆开";
                        break;
                    case "40":
                        content = "备电故障";
                        break;
                    case "41":
                        content = "主电故障";
                        break;
                    case "42":
                        content = "无线模块故障";
                        break;
                    case "43":
                        content = "GSM模块故障";
                        break;
                    case "44":
                        content = "备电低电";
                        break;
                    case "4F":
                        content = "测试";
                        break;
                    case "50":
                        content = "门磁低电";
                        break;
                }

            }
            // 判断指令类型，获得响应消息体结构
            switch (informationType) {
                case "01": // 消息内容： 警告类型（1字节）+警告等级（1字节）+警告内容（1字节）+信号强度（1字节）+电量（1字节)
                    break;
                case "02": // 警告类别（1字节）+警告等级（1字节）+警告内容（第九位）（1字节）+数值（3字节，前两个字节为数据，高位在前，后一个字节为数据类型）+信号强度（1字节）+电量（1字节）
                    break;
                case "03": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+数值1（3字节）+数值2（3字节）+信号强度（1字节）+电量（1字节）
                    break;
                case "04": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+数值1（3字节）+数值2（3字节）+数值3（3字节）+信号强度（1字节）+电量（1字节）
                    break;
                case "05": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+信号强度（1字节）
                    break;
                case "06": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+数值（3字节，前两个字节为数据，高位在前，后一个字节为数据类型）+信号强度（1字节）
                    break;
                case "07": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+防区号（1字节）+信号强度（1字节）
                    areaNumber = data.get(10);
                    signal = data.get(11);
                case "08": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+防区号（1字节）+数值1（3字节）+信号强度（1字节）
                    break;
                case "09": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+防区号（1字节）+数值1（3字节）+数值2+信号强度（1字节）
                    break;
                case "0A": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+防区号（1字节）+数值1（3字节）+数值2+数值3+信号强度（1字节）
                    break;
                case "0B": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+防区号（1字节）+电量（1字节）+信号强度（1字节）
                    break;
                case "0C": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+防区号（1字节）+数值1（3字节）+电量（1字节）+信号强度（1字节）
                    break;
                case "0D": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+防区号（1字节）+数值1（3字节）+数值2+电量（1字节）+信号强度（1字节）
                    break;
                case "0E": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+防区号（1字节）+数值1（3字节）+数值2+数值3+电量（1字节）+信号强度（1字节）
                    break;
                case "0F": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+防区号（1字节）+数值数量（1字节）+数值1（3字节）+数值N+信号强度（1字节）
                    break;
                case "10": // 警告类别（1字节）+警告等级（1字节）+警告内容（1字节）+数值数量（1字节）+数值1（3字节）+数值N+信号强度（1字节）
                    break;
            }
        } else if ("02".equals(command)) { // 登录
            if ("02".equals(informationType)) {
                int length = Integer.parseInt(data.get(7));
                try {
                    deviceId = getData(data, 8, length);
                    deviceType = getData(data, 8 + length, 1);
                    gateWayNember = getData(data, 9 + length, 20);
                    signal = getData(data, 29 + length, 1);
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        } else if ("01".equals(command)) { // 心跳
            if ("02".equals(informationType)) {
                signal = data.get(7);
                mark = "true";
            }
        }
        //为报警
        JSONObject jsonParamN = new JSONObject();
        if (flag) {
            jsonParamN.put("deviceClassify", "5");
            jsonParamN.put("number", number+areaNumber);
            jsonParamN.put("interfaceType", "1");
            jsonParamN.put("alarmtime", time);
            jsonParamN.put("alarmTypeName", alarmTypeName);
            jsonParamN.put("areaNumber", areaNumber);
            jsonParamN.put("content", content);
            jsonParamN.put("state", "2");
            if (!StringUtils.isEmpty(areaNumber)) {
                // 添加手报的报警记录
                //fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                JSONObject jsonObject = new JSONObject(jsonParamN);
                asyncService.updateDeviceCurrentState(jsonObject);
                // 添加网关的报警记录
                jsonParamN.put("number", number);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                asyncService.updateDeviceCurrentState(jsonParamN);
            } else {
                // 添加网关的报警记录
                jsonParamN.put("number", number);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                asyncService.updateDeviceCurrentState(jsonParamN);
            }


        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "今日数据变化");
            jsonObject.put("value", 0);
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);
            //rest调用平时数据添加接口：
            jsonParamN.put("paraminfo", jsonArray);
            jsonParamN.put("number", number);
            jsonParamN.put("time", time);
            //return RespEntity.success(jsonParamN);
            fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
            //异步更新设备状态
            jsonParamN.put("state", "1");
            asyncService.updateDeviceCurrentState(jsonParamN);
            //更新部件状态
            asyncService.update_user_transmission_state(jsonParamN);
        }
        return RespEntity.success();
    }

    /**
     * 从集合中取出一定长度的数据
     *
     * @param list
     * @param start
     * @param length
     * @return
     */
    public String getData(List<String> list, Integer start, Integer length) {
        if (start < 0 || length < 0 || start + length > list.size()) {
            return "error";
        }
        StringBuffer stringBuffer = new StringBuffer();
        if (length == 1) {
            return list.get(start);
        } else{
            for (int i = start; i <= start + length; i++) {
                stringBuffer.append(list.get(i));
            }
        }

        return String.valueOf(stringBuffer);
    }

    /**
     * @Author YangYu
     * @Description sos一键报警（吉凯达打电话）
     * @Date Created in 13:52 2021/7/26
     * @Param [jsonParam]
     */

    public RespEntity deviceDataChangedJKDSOS(JSONObject jsonParam) throws Exception {
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("JKDSOS");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        if (jsonParam.toString().equals("{}")){
            return RespEntity.success();
        }
        //转发对象
        JSONObject jsonParamN = new JSONObject();
        //报警时间
        String time = DateUtil.now();
        //心跳数据
        if (jsonParam.containsKey("iccid")){
            String[] imeis = jsonParam.getStr("imei").split("/");
            jsonParamN.put("number",imeis[1]);
            jsonParamN.put("state","1");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }else if (jsonParam.containsKey("payload")){
            if (jsonParam.getStr("payload").equals("ALARM")){
                jsonParamN.put("deviceClassify","5");
                jsonParamN.put("number",jsonParam.getStr("imei"));
                jsonParamN.put("interfaceType","1");
                jsonParamN.put("alarmtime",time);
                jsonParamN.put("alarmTypeName","SOS预警");
                jsonParamN.put("content","SOS预警");
                fireFightingiot(jsonParamN,"communication","notificationAlarmHandel","alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        }else if (jsonParam.containsKey("msgId")){

        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description sos一键报警（吉凯达打电话）
     * @Date Created in 13:52 2021/7/26
     * @Param [jsonParam]
     */

    public RespEntity deviceDataChangedMGSOS(MultiValueMap<String,Object> formData) throws Exception {
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(formData.toString());
        alarmAllDeviceDataChanged.setType("MGSOS");
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        //转发对象
        JSONObject jsonParamN = new JSONObject();
        //报警时间
        String time = DateUtil.now();

        if (formData.containsKey("data")){
            JSONObject data = new JSONObject(formData.getFirst("data"));
            //设备号
            jsonParamN.put("number",data.getStr("serialNum"));
            if (data.getStr("type").equals("powerOn")){
                jsonParamN.put("state","1");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }else {
                jsonParamN.put("state","3");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        }else if (formData.getFirst("sos").equals("true")){
            //设备号
            jsonParamN.put("number",formData.getFirst("serialNum"));
            jsonParamN.put("deviceClassify","5");
            jsonParamN.put("interfaceType","1");
            jsonParamN.put("alarmtime",time);
            jsonParamN.put("alarmTypeName","SOS预警");
            jsonParamN.put("content","SOS预警");
            fireFightingiot(jsonParamN,"communication","notificationAlarmHandel","alarmInfo");
            //异步更新设备状态
            jsonParamN.put("state","2");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 三江用户传输装置
     * @Date Created in 9:45 2022/10/27
     * @Param [jsonParam]
     */

    public RespEntity sanjiangAutoNetwork(JSONObject jsonParam)  {
        //设备号
        String number = jsonParam.getStr("deviceId");
        //时间
        String time = jsonParam.getStr("at");
        //报警数据
        String data = jsonParam.getStr("data");
        //报警类型
        String alarmTypeName = "";
        //报警内容
        String content = "";
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number",number);
        if (data.contains("火警")){
            alarmTypeName = "火警";
            content = data;
            //异步更新设备状态
            jsonParamN.put("state","2");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }else if (data.contains("请求")){
            alarmTypeName = "系统事件";
            content = data;
            //异步更新设备状态
            jsonParamN.put("state","2");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }else if (data.contains("故障")){
            alarmTypeName = "故障";
            content = data;
            //异步更新设备状态
            jsonParamN.put("state","2");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }else if (data.contains("复位")){
            alarmTypeName = "系统事件";
            content = data;
            //异步更新设备状态
            jsonParamN.put("state","2");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }else if (data.equals("设备上线")){
            alarmTypeName = "系统事件";
            content = data;
            jsonParamN.put("state","1");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }else if (data.equals("设备上线")){
            alarmTypeName = "系统事件";
            content = data;
            jsonParamN.put("state","3");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        jsonParamN.put("deviceClassify","5");
        jsonParamN.put("interfaceType","1");
        jsonParamN.put("alarmtime",time);
        jsonParamN.put("alarmTypeName",alarmTypeName);
        jsonParamN.put("content",content);
        fireFightingiot(jsonParamN,"communication","notificationAlarmHandel","alarmInfo");
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 海康用户传输装置
     * @Date Created in 14:11 2023/9/21
     * @Param [jsonParam]
     */

    public RespEntity autoNetHik(JSONObject jsonParam){
        //原始数据
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChanged.setType("autoNetDahua");
        //alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
        //用于下发指令设备ID
        String dev_id = jsonParam.getStr("dev_id");
        //数据
        String code = jsonParam.getStr("code");
        //时间
        String realTime = DateUtil.now();
        //报警类型
        String alarmTypeName = "";
        //报警内容
        String content = "";
        //主机号
        Integer hostNumber = hexToInt(code.substring(34,36)+code.substring(32,34)+code.substring(30,32)+code.substring(28,30)+code.substring(26,28)+code.substring(24,26));
        //平台设备编号
        String number = "";
        //报警标识
        boolean flag = false;
        //命令字节
        Integer command = hexToInt(code.substring(52,54));
        JSONObject jsonParamN = new JSONObject();
        //只解析用传发送数据
        if (command == 2){
            //类型标志
            Integer type = hexToInt(code.substring(54,56));
            //上传建筑消防设施部件运行状态
            if (type == 2){
                //系统类型标志
                Integer systemType = hexToInt(code.substring(58,60));
                String systemTypeName = systemTypeHik(systemType);
                //系统地址
                Integer systemAddr = hexToInt(code.substring(60,62));
                //部件类型
                Integer partType = hexToInt(code.substring(62,64));
                String partTypeName = getComponentName(partType);
                //部件地址
                String partAddr = code.substring(64,72);
                JSONObject partAddrJ = getComponentCodeHik(partAddr);
                //回路
                String loop = partAddrJ.getStr("loop");
                //地址
                String addr = partAddrJ.getStr("addr");
                //部件状态0500
                String partState = code.substring(72,76);
                String partStateB = HexUtils.hexToBinaryStringN(partState.substring(2,4)+partState.substring(0,2));
                if (partStateB.charAt(14) == '1'){
                    alarmTypeName = "火警";
                    content = content + "火警、";
                    flag = true;
                }else if (partStateB.charAt(13) == '1'){
                    alarmTypeName = "故障";
                    content = content + "故障、";
                    flag = true;
                }else if (partStateB.charAt(12) == '1'){
                    alarmTypeName = "系统事件";
                    content = content + "屏蔽、";
                    flag = true;
                }else if (partStateB.charAt(11) == '1'){
                    alarmTypeName = "系统事件";
                    content = content + "监管、";
                    flag = true;
                }else if (partStateB.charAt(10) == '1'){
                    alarmTypeName = "系统事件";
                    content = content + "启动开启、";
                    flag = true;
                }else if (partStateB.charAt(9) == '1'){
                    alarmTypeName = "系统事件";
                    content = content + "反馈、";
                    flag = true;
                }else if (partStateB.charAt(8) == '1'){
                    alarmTypeName = "系统事件";
                    content = content + "延时状态、";
                    flag = true;
                }else if (partStateB.charAt(7) == '1'){
                    alarmTypeName = "故障";
                    content = content + "电源故障、";
                    flag = true;
                }
                if (flag){
                    content = systemTypeName+"、"+partTypeName+"、"+content;
                    number = hostNumber+"-"+systemAddr+"-"+loop+"-"+addr;
                    jsonParamN.put("deviceClassify","5");
                    jsonParamN.put("number",number);
                    jsonParamN.put("interfaceType","1");
                    jsonParamN.put("alarmtime",realTime);
                    jsonParamN.put("alarmTypeName",alarmTypeName);
                    jsonParamN.put("content",content.substring(0,content.length()-1));
                    fireFightingiot(jsonParamN,"communication","notificationAlarmHandel","alarmInfo");
                    //异步更新设备状态
                    jsonParamN.put("state","2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }
            }else if (type == 21){//上传用户信息传输装置运行状态
                //用户传输装置状态
                String transmissionState = HexUtils.hexToBinaryString(code.substring(58,60));
                if (transmissionState.charAt(6) == '1'){
                    alarmTypeName = "火警";
                    content = content+"用传火警、";
                    flag = true;
                }else if (transmissionState.charAt(5) == '1'){
                    alarmTypeName = "故障";
                    content = content+"用传故障、";
                    flag = true;
                }else if (transmissionState.charAt(4) == '1'){
                    alarmTypeName = "故障";
                    content = content+"用传主电故障、";
                    flag = true;
                }else if (transmissionState.charAt(3) == '1'){
                    alarmTypeName = "故障";
                    content = content+"用传备电故障、";
                    flag = true;
                }else if (transmissionState.charAt(2) == '1'){
                    alarmTypeName = "故障";
                    content = content+"与监控中心通信信道故障、";
                    flag = true;
                }else if (transmissionState.charAt(1) == '1'){
                    alarmTypeName = "故障";
                    content = content+"监测连接线路故障、";
                    flag = true;
                }
                if (flag){
                    jsonParamN.put("deviceClassify","5");
                    jsonParamN.put("number",hostNumber);
                    jsonParamN.put("interfaceType","1");
                    jsonParamN.put("alarmtime",realTime);
                    jsonParamN.put("alarmTypeName",alarmTypeName);
                    jsonParamN.put("content",content.substring(0,content.length()-1));
                    fireFightingiot(jsonParamN,"communication","notificationAlarmHandel","alarmInfo");
                    //异步更新设备状态
                    jsonParamN.put("state","2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }
            }else if (type == 24){//上传用户信息传输装置操作信息
                //用户传输装置操作状态
                String transmissionOperateState = HexUtils.hexToBinaryString(code.substring(58,60));
                if (transmissionOperateState.charAt(7) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传复位、";
                    flag = true;
                }else if (transmissionOperateState.charAt(6) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传消音、";
                    flag = true;
                }else if (transmissionOperateState.charAt(5) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传手动报警、";
                    flag = true;
                }else if (transmissionOperateState.charAt(4) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传警情消除、";
                    flag = true;
                }else if (transmissionOperateState.charAt(3) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"用传自检、";
                    flag = true;
                }else if (transmissionOperateState.charAt(2) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"查岗应答、";
                    flag = true;
                }else if (transmissionOperateState.charAt(1) == '1'){
                    alarmTypeName = "系统事件";
                    content = content+"测试、";
                    flag = true;
                }
                if (flag){
                    jsonParamN.put("deviceClassify","5");
                    jsonParamN.put("number",hostNumber);
                    jsonParamN.put("interfaceType","1");
                    jsonParamN.put("alarmtime",realTime);
                    jsonParamN.put("alarmTypeName",alarmTypeName);
                    jsonParamN.put("content",content.substring(0,content.length()-1));
                    fireFightingiot(jsonParamN,"communication","notificationAlarmHandel","alarmInfo");
                    //异步更新设备状态
                    jsonParamN.put("state","2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                }
            }else if (type == 25){//上传用户信息传输装置软件版本
                jsonParamN.put("number", hostNumber);
                jsonParamN.put("time", realTime);
                asyncService.update_user_transmission_state(jsonParamN);
            }
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 部件地址解析（海康）
     * @Date Created in 16:39 2023/9/25
     * @Param [componentCode]
     */

    public static JSONObject getComponentCodeHik(String hex){

        if (hex.length() % 2 != 0) {
            throw new IllegalArgumentException("输入的十六进制字符串长度必须为偶数");
        }

        StringBuilder reversed = new StringBuilder();
        for (int i = hex.length(); i > 0; i -= 2) {
            reversed.append(hex, i - 2, i);
        }

        int uiPartAddr = Integer.parseUnsignedInt(reversed.toString(), 16);
        System.out.println(uiPartAddr);
        //回路
        int loop = uiPartAddr >> 16;
        //地址
        int addr =  uiPartAddr & 0x0000ffff;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("loop",loop);
        jsonObject.put("addr",addr);
        return jsonObject;
    }

    /**
     * @Author YangYu
     * @Description 海康用传系统类型
     * @Date Created in 上午11:37 2025/3/25
     * @Param [code]
     */

    private String systemTypeHik(Integer code){

        if (code == 0){
            return "通用";
        }else if (code == 1){
            return "火灾报警系统";
        }else if (code == 10){
            return "消防联动控制器";
        }else if (code == 11){
            return "消火栓系统";
        }else if (code == 12){
            return "自动喷水灭火系统";
        }else if (code == 13){
            return "气体灭火系统";
        }else if (code == 14){
            return "水喷雾灭火系统（泵启动方式）";
        }else if (code == 15){
            return "水喷雾灭火系统（压力容器启动方式）";
        }else if (code == 16){
            return "泡沫灭火系统";
        }else if (code == 17){
            return "干粉灭火系统";
        }else if (code == 18){
            return "防烟排烟系统";
        }else if (code == 19){
            return "防火门及卷帘系统";
        }else if (code == 20){
            return "消防电梯";
        }else if (code == 21){
            return "消防应急广播";
        }else if (code == 22){
            return "消防应急照明和疏散指示系统";
        }else if (code == 23){
            return "消防电源";
        }else if (code == 24){
            return "消防电话";
        }
        return "";
    }
    public  String hxTime(String time){
        String year = hex16To10(time.substring(0, 2))+"";
        String month = getStr2(hex16To10(time.substring(2, 4))+"");
        String day = getStr2(hex16To10(time.substring(4, 6))+"");
        String hour = getStr2(hex16To10(time.substring(6, 8))+"");
        String minute = getStr2(hex16To10(time.substring(8, 10))+"");
        String second = getStr2(hex16To10(time.substring(10, 12))+"");
        String realTime = "20"+year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second; //yyyy-MM-dd HH:mm:ss
        return realTime;
    }

    /**
     * @Author YangYu
     * @Description 状态字1
     * @Date Created in 11:41 2021/1/19
     * @Param [code]
     */
    public static String getStatusWord(String code) {
        if (code.length() == 1) {
            code = "0" + code;
        }
        Map<String, String> map = new HashMap<>();
        map.put("01", "复位");
        map.put("02", "主电故障");
        map.put("03", "主电恢复");
        map.put("04", "备电故障");
        map.put("05", "备电恢复");
        map.put("06", "手动允许");
        map.put("07", "自动允许");
        map.put("08", "喷洒允许");
        map.put("09", "本次开机");
        map.put("0A", "上次关机");
        map.put("0B", "自检");
        map.put("0C", "全关");
        map.put("0D", "直控禁止");
        map.put("0E", "直控允许");
        map.put("0F", "手动禁止");
        map.put("10", "自动禁止");
        map.put("11", "喷洒禁止");
        map.put("12", "总线故障");
        map.put("13", "延时");
        map.put("14", "延时状态");
        map.put("15", "延时结束");
        map.put("16", "自检结束");
        map.put("17", "全开");
        map.put("18", "消音");
        map.put("19", "全部自动");
        map.put("20", "部分自动");
        map.put("21", "模拟联动");
        map.put("22", "监控状态");
        map.put("23", "调试状态");
        map.put("24", "用户登录");
        return map.get(code);
    }


    /**
     * @Author YangYu
     * @Description 探测器类型
     * @Date Created in 11:41 2021/1/19
     * @Param [code]
     */
    public static String getDetectorType(String code) {
        if (code.length() == 1) {
            code = "0" + code;
        }
        Map<String, String> map = new HashMap<>();
        map.put("00","未定义") ;
        map.put("04","报警接口");
        map.put("08","缆式感温");
        map.put("12","消防广播");
        map.put("16","消火栓泵");
        map.put("20","送风机") ;
        map.put("24","送风阀") ;
        map.put("28","防火门") ;
        map.put("32","空调机组");
        map.put("36","水幕电磁");
        map.put("40","火灾示盘");
        map.put("44","消防电源");
        map.put("48","防盗模块");
        map.put("52","层号灯") ;
        map.put("56","急停按钮");
        map.put("60","空压机") ;
        map.put("64","雨淋阀") ;
        map.put("68","外控允许");
        map.put("72","备用工作");
        map.put("76","未定义") ;
        map.put("80","未定义") ;
        map.put("84","吸气火警");
        map.put("88","未定义") ;
        map.put("92","未定义") ;
        map.put("96","未定义") ;
        map.put("100","湿式报警阀");
        map.put("01", "离子感烟");
        map.put("05", "可燃气体");
        map.put("09", "模拟感温");
        map.put("13", "讯响器");
        map.put("17", "喷淋泵");
        map.put("21", "新风机");
        map.put("25", "电磁阀");
        map.put("29", "压力开关");
        map.put("33", "柴油发电");
        map.put("37", "气体启动");
        map.put("41", "闸阀");
        map.put("45", "紧急照明");
        map.put("49", "信号碟阀");
        map.put("53", "设备停动");
        map.put("57", "雨淋泵");
        map.put("61", "联动电源");
        map.put("65", "感温棒");
        map.put("69", "外控禁止");
        map.put("73", "内部设备");
        map.put("77", "未定义");
        map.put("81", "消火栓");
        map.put("85", "吸气预警");
        map.put("89", "未定义");
        map.put("93", "未定义");
        map.put("97", "交流电源");
        map.put("101", "疏散门");
        map.put("02", "点型感温");
        map.put("06", "红外对射");
        map.put("10", "复合探测");
        map.put("14", "消防电话");
        map.put("18", "稳压泵");
        map.put("22", "防火阀");
        map.put("26", "卷帘门中");
        map.put("30", "水流指示");
        map.put("34", "照明配电");
        map.put("38", "气体停动");
        map.put("42", "高位水箱");
        map.put("46", "疏导指示");
        map.put("50", "防排烟阀");
        map.put("54", "泵故障");
        map.put("58", "上位机");
        map.put("62", "多线盘锁");
        map.put("66", "故障输出");
        map.put("70", "备用指示");
        map.put("74", "紧急求助");
        map.put("78", "干粉灭火");
        map.put("82", "缆式感温");
        map.put("86", "未定义");
        map.put("90", "总线");
        map.put("94", "接地故障");
        map.put("98", "备用电源");
        map.put("102","水位");
        map.put("03", "点型感烟");
        map.put("07", "紫外感光");
        map.put("11", "手动按钮");
        map.put("15", "消火栓");
        map.put("19", "排烟机");
        map.put("23", "排烟阀");
        map.put("27", "卷帘门下");
        map.put("31", "电梯");
        map.put("35", "动力配电");
        map.put("39", "从机");
        map.put("43", "泡沫泵");
        map.put("47", "喷洒指示");
        map.put("51", "水幕泵");
        map.put("55", "急启按钮");
        map.put("59", "回路");
        map.put("63", "部分设备");
        map.put("67", "环路开关");
        map.put("71", "门灯");
        map.put("75", "未定义");
        map.put("79", "未定义");
        map.put("83", "吸气感烟");
        map.put("87", "未定义");
        map.put("91", "未定义");
        map.put("95", "联动公式");
        map.put("99", "键盘");
        return map.get(code);
    }

    /**
     * @Author YangYu
     * @Description 信息类型
     * @Date Created in 11:41 2021/1/19
     * @Param [code]
     */
    public static String getInformationType(String code) {
        Map<String, String> map = new HashMap<>();
        map.put("00", "正常");
        map.put("01", "火警");
        map.put("02", "监管");
        map.put("03", "启动");
        map.put("04", "反馈");
        map.put("05", "隔离（屏蔽）");
        map.put("06", "取消隔离（取消屏蔽）");
        map.put("07", "故障");
        map.put("08", "故障恢复（消除）");
        map.put("09", "动作");
        map.put("0A", "停止");
        map.put("0B", "预警");
        map.put("0C", "预警恢复");
        map.put("0D", "报警");
        map.put("0E", "报警恢复");
        map.put("0F", "停动");
        map.put("10", "离线");
        map.put("11", "离线恢复");
        map.put("12", "测试");
        map.put("13", "结束测试");
        map.put("14", "报脏");
        map.put("15", "反馈恢复");
        map.put("16", "设备自检");
        map.put("17", "预留");
        map.put("18", "预留");
        map.put("19", "预留");
        map.put("20", "消防主机状态");
        return map.get(code);
    }


    /**
     * @Author YangYu
     * @Description 系统类型
     * @Date Created in 11:41 2021/1/19
     * @Param [code]
     */
    public static String getSystemType(String code) {
        Map<String, String> map = new HashMap<>();
        map.put("01", "火灾自动报警系统");
        map.put("02", "自动喷水灭火系统");
        map.put("03", "消火栓系统");
        map.put("04", "电气火灾监控系统");
        map.put("05", "可燃气体探测系统");
        map.put("06", "防火门监控系统");
        map.put("07", "电源监控系统");
        map.put("08", "智慧电力");
        map.put("09", "智慧农业");
        map.put("0a", "预留");
        return map.get(code);
    }

    /**
     * 16进制转10进制
     * @param strHex
     * @return
     */
    public static int hex16To10(String strHex) {
        BigInteger lngNum = new BigInteger(strHex, 16);
        return lngNum.intValue();
    }

    /**
     * 年月日匹配
     * @param str
     * @return
     */
    public String getStr2(String str){
        if(str.length() == 1){
            return "0"+str;
        }
        return str;
    }

    /**
     * 16进制 转 ASCII码
     * @param “3030313030312d30303300000000000000000000”
     * @return 001001-003
     */
    public String convertHexToString(String hex) {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            if (!output.equals("00")) {
                //convert hex to decimal
                int decimal = Integer.parseInt(output, 16);
                //convert the decimal to character
                sb.append((char) decimal);

                temp.append(decimal);
            }
        }

        return sb.toString();

    }

    /**
     * 将毫秒转化为日期(格式:yyyy-MM-dd hh:mm:ss)
     * @param l
     * @return
     * @throws Exception
     */
    public String contextLoads(Long l) throws Exception {

        java.text.SimpleDateFormat sdf1=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        Date date = new Date(l);
        String str1 = sdf1.format(date);
        java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date2 = sdf.parse(str1);
        String str2 = sdf.format(date2);
        return str2;
    }


}
